package com.rykj.widget.bottomnavigation;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.StateListDrawable;
import android.util.AttributeSet;

import com.rykj.R;
import com.rykj.util.SelectorFactory;


/**
 * Description ：
 * <p/>
 * Created by ycw on 2017/5/5.
 */

public class BottomLayoutTextView extends androidx.appcompat.widget.AppCompatTextView implements
        BottomObserver {

    private Context context;
    private Drawable selectDrawable;
    private Drawable unSelectDrawable;
    private Direction direction = Direction.TOP;

    public BottomLayoutTextView(Context context) {
        this(context, null);
    }

    public BottomLayoutTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public BottomLayoutTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        init(attrs, defStyleAttr);
    }

    private void init(AttributeSet attrs, int defStyleAttr) {
        TypedArray ta = context
                .obtainStyledAttributes(attrs, R.styleable.BottomLayoutTextView, defStyleAttr, 0);
        if (ta != null) {
            selectDrawable = ta.getDrawable(R.styleable.BottomLayoutTextView_btv_select_drawable);
            unSelectDrawable = ta
                    .getDrawable(R.styleable.BottomLayoutTextView_btv_unselect_drawable);
            Direction direction = Direction.values()[ta
                    .getInt(R.styleable.BottomLayoutTextView_btv_direction, 0)];
            setDrawableDirection(direction);
            ta.recycle();
        }
    }

    public void setDrawableDirection(Direction direction) {
        this.direction = direction;
        createDrawable(direction);
    }

    /**
     * 设置某一方向的图片
     */
    public void createDrawable(Direction direction) {
        StateListDrawable stateListDrawable = SelectorFactory.newGeneralSelector()
                .setDefaultDrawable(unSelectDrawable).setPressedDrawable(selectDrawable)
                .setSelectedDrawable(selectDrawable).create();
        setCompoundDrawablesWithIntrinsicBounds(direction == Direction.LEFT?stateListDrawable:null,
                direction == Direction.TOP?stateListDrawable:null,
                direction == Direction.RIGHT?stateListDrawable:null,
                direction == Direction.BOTTOM?stateListDrawable:null);
    }

    @Override
    public void update(BottomObserver observer) {
        setSelected(observer.equals(this));
    }

    public void setSelctedDrawable(Drawable drawable) {
        selectDrawable = drawable;
    }

    public void setUnSelctedDrawable(Drawable unDrawable) {
        unSelectDrawable = unDrawable;
    }

    public enum Direction {
        LEFT,
        TOP,
        RIGHT,
        BOTTOM
    }
}
